/**
 * 统计 killNextAccuracy (0/1 数组) 的表现
 * 可用于评估杀号准确率走势、连续错误风险、稳定性等
 *
 * @param {number[]} data - 由 0（杀错）和 1（杀对）组成的数组
 * @param {Object}  [options]
 * @param {number}  [options.decay=0.9] - 衰减因子 (0-1)，越靠近当前权重越大
 * @returns {Object} stats - 统计指标对象
 */
function calcAccuracySummary(data, options = {}) {
  if (!Array.isArray(data) || data.length === 0) {
    return {
      count: 0,
      correctCount: 0,
      incorrectCount: 0,
      accuracyRate: 0,
      maxConsecutiveCorrect: 0,
      maxConsecutiveIncorrect: 0,
      consecutiveCorrectSegments: 0,
      consecutiveIncorrectSegments: 0,
      avgConsecutiveCorrect: 0,
      avgConsecutiveIncorrect: 0,
      currentConsecutiveCorrect: 0,
      currentConsecutiveIncorrect: 0,
      last10AccuracyRate: 0,
      decayAccuracyScore: 0,
      volatilityScore: 0,
      lastKillCorrect: 0,
      score: 0,
    };
  }

  // === 初始化统计变量 ===
  let correctCount = 0;
  let incorrectCount = 0;
  let maxConsecutiveCorrect = 0;
  let maxConsecutiveIncorrect = 0;
  let currentConsecutiveCorrect = 0;
  let currentConsecutiveIncorrect = 0;
  let totalConsecutiveCorrect = 0;
  let totalConsecutiveIncorrect = 0;
  let consecutiveCorrectSegments = 0;
  let consecutiveIncorrectSegments = 0;
  let changeCount = 0;

  const decay = options.decay ?? 0.9;
  const last10 = data.slice(-10);

  // === 衰减加权准确率 ===
  const decayAccuracyScore = data.reduceRight((acc, cur, i, arr) => {
    const weight = Math.pow(decay, arr.length - 1 - i);
    return acc + cur * weight;
  }, 0);

  // === 遍历数据 ===
  for (let i = 0; i < data.length; i++) {
    const val = data[i];

    if (i > 0 && data[i] !== data[i - 1]) changeCount++;

    if (val === 1) {
      correctCount++;
      currentConsecutiveCorrect++;
      if (currentConsecutiveIncorrect > 0) {
        maxConsecutiveIncorrect = Math.max(
          maxConsecutiveIncorrect,
          currentConsecutiveIncorrect
        );
        totalConsecutiveIncorrect += currentConsecutiveIncorrect;
        consecutiveIncorrectSegments++;
        currentConsecutiveIncorrect = 0;
      }
    } else {
      incorrectCount++;
      currentConsecutiveIncorrect++;
      if (currentConsecutiveCorrect > 0) {
        maxConsecutiveCorrect = Math.max(
          maxConsecutiveCorrect,
          currentConsecutiveCorrect
        );
        totalConsecutiveCorrect += currentConsecutiveCorrect;
        consecutiveCorrectSegments++;
        currentConsecutiveCorrect = 0;
      }
    }
  }

  // 结尾段处理
  if (currentConsecutiveCorrect > 0) {
    maxConsecutiveCorrect = Math.max(
      maxConsecutiveCorrect,
      currentConsecutiveCorrect
    );
    totalConsecutiveCorrect += currentConsecutiveCorrect;
    consecutiveCorrectSegments++;
  }
  if (currentConsecutiveIncorrect > 0) {
    maxConsecutiveIncorrect = Math.max(
      maxConsecutiveIncorrect,
      currentConsecutiveIncorrect
    );
    totalConsecutiveIncorrect += currentConsecutiveIncorrect;
    consecutiveIncorrectSegments++;
  }

  // === 结果 ===
  const accuracyRate = correctCount / data.length;
  const avgConsecutiveCorrect = consecutiveCorrectSegments
    ? totalConsecutiveCorrect / consecutiveCorrectSegments
    : 0;
  const avgConsecutiveIncorrect = consecutiveIncorrectSegments
    ? totalConsecutiveIncorrect / consecutiveIncorrectSegments
    : 0;
  const last10AccuracyRate =
    last10.filter((v) => v === 1).length / last10.length;
  const volatilityScore = data.length > 1 ? changeCount / (data.length - 1) : 0;
  const lastKillCorrect = data[data.length - 1] || 0;

  // 一个可调的综合评分 (范围 0-1，越高越好)
  const score =
    accuracyRate * 0.5 +
    (decayAccuracyScore / data.length) * 0.3 +
    (1 - volatilityScore) * 0.2;

  return {
    count: data.length,
    correctCount,
    incorrectCount,
    accuracyRate,
    maxConsecutiveCorrect,
    maxConsecutiveIncorrect,
    consecutiveCorrectSegments,
    consecutiveIncorrectSegments,
    avgConsecutiveCorrect,
    avgConsecutiveIncorrect,
    currentConsecutiveCorrect,
    currentConsecutiveIncorrect,
    last10AccuracyRate,
    decayAccuracyScore,
    volatilityScore,
    lastKillCorrect,
    score,
  };
}

// === 中文字段映射（方便输出报表） ===
const ACCURACY_SUMMARY_CN_MAP = {
  count: "统计次数",
  correctCount: "正确次数",
  incorrectCount: "错误次数",
  accuracyRate: "准确率",
  maxConsecutiveCorrect: "最大连续正确",
  maxConsecutiveIncorrect: "最大连续错误",
  consecutiveCorrectSegments: "正确段数",
  consecutiveIncorrectSegments: "错误段数",
  avgConsecutiveCorrect: "平均连续正确",
  avgConsecutiveIncorrect: "平均连续错误",
  currentConsecutiveCorrect: "当前连续正确",
  currentConsecutiveIncorrect: "当前连续错误",
  last10AccuracyRate: "近10期准确率",
  decayAccuracyScore: "衰减准确率得分",
  volatilityScore: "波动率",
  lastKillCorrect: "最近一次是否杀对",
  score: "综合评分",
};

module.exports = { calcAccuracySummary, ACCURACY_SUMMARY_CN_MAP };
